package com.ckf.serene.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ckf.serene.config.WeChatConfig;
import com.ckf.serene.domain.VipOrderParam;
import com.ckf.serene.domain.WXPayParam;
import com.ckf.serene.domain.WeChatTransferParam;
import com.ckf.serene.domain.WxRefundParam;
import com.ckf.serene.enums.WXPayBank;
import com.ckf.serene.exception.CustomException;
import com.ckf.serene.sdk.WXPayUtil;
import com.ckf.serene.service.WeChatPayService;
import com.ckf.serene.utils.IPHelper;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.ijpay.core.IJPayHttpResponse;
import com.ijpay.core.enums.RequestMethod;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.*;
import com.ijpay.core.utils.DateTimeZoneUtil;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.enums.WxDomain;
import com.ijpay.wxpay.model.GetTransferInfoModel;
import com.ijpay.wxpay.model.RefundModel;
import com.ijpay.wxpay.model.RefundQueryModel;
import com.ijpay.wxpay.model.TransferModel;
import com.ijpay.wxpay.model.v3.Amount;
import com.ijpay.wxpay.model.v3.Payer;
import com.ijpay.wxpay.model.v3.UnifiedOrderModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信服务实现类
 *
 * @author serence
 * @date 2021/11/6 23:39
 */
@Slf4j
@Service
public class WeChatPayServiceImpl implements WeChatPayService {

    /**
     * 序列号
     */
    private String serialNo;

    /**
     * 获取证书序列号
     *
     * @return 证书序列号证书序列号
     */
    private String getSerialNumber() {
        if (StrUtil.isEmpty(serialNo)) {
            // 获取证书序列号
            X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(WeChatConfig.certPath));
            serialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        }
        return serialNo;
    }

    /**
     * 小程序支付V3
     *
     * @param payParam 支付参数类
     * @return
     */
    @Override
    public Map<String, String> appletsV3(WXPayParam payParam) {
        try {
            String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3);
            UnifiedOrderModel unifiedOrderModel = new UnifiedOrderModel()
                    .setAppid(WeChatConfig.APP_ID)
                    .setMchid(WeChatConfig.MCH_ID)
                    .setDescription(payParam.getBody())
                    .setOut_trade_no(payParam.getOutTradeNo())
                    .setTime_expire(timeExpire)
                    .setNotify_url("外网域名" + WeChatConfig.Payment_Callback)
                    .setAmount(new Amount().setTotal(payParam.getTotalFee().intValue()))
                    .setPayer(new Payer().setOpenid(payParam.getOpenId()));

            log.info("统一下单参数 {}", JSONUtil.toJsonStr(unifiedOrderModel));
            IJPayHttpResponse response = WxPayApi.v3(
                    RequestMethod.POST,
                    WxDomain.CHINA.toString(),
                    WxApiType.JS_API_PAY.toString(),
                    WeChatConfig.MCH_ID,
                    getSerialNumber(),
                    null,
                    WeChatConfig.keyPath,
                    JSONUtil.toJsonStr(unifiedOrderModel)
            );
            log.info("统一下单响应 {}", response);

            if (response.getStatus() == 200) {
                // 根据证书序列号查询对应的证书来验证签名结果
                boolean verifySignature = WxPayKit.verifySignature(response, WeChatConfig.platformCertPath);
                log.info("verifySignature: {}", verifySignature);
                if (verifySignature) {
                    String body = response.getBody();
                    JSONObject jsonObject = JSONUtil.parseObj(body);
                    String prepayId = jsonObject.getStr("prepay_id");
                    Map<String, String> map = WxPayKit.jsApiCreateSign(WeChatConfig.APP_ID, prepayId, WeChatConfig.keyPath);
                    log.info("唤起支付参数 {}", map);
                    return map;
                }
            }
            String s = JSONUtil.toJsonStr(response);
            Map maps = (Map) JSON.parse(s);
            return maps;
        } catch (Exception e) {
            e.printStackTrace();

        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 微信支付成功回调通知
     *
     * @param request 回调信息
     * @return
     */
    @Override
    public String weChatPaySuccess(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        log.info("支付通知： {}" + xmlMsg);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        String returnCode = params.get("return_code");
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 业务逻辑处理
                // 更新订单信息
                // 发送通知......
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 微信退款
     *
     * @param wxRefundParam 微信退款参数类
     * @return
     */
    @Override
    public Map<String, String> weChatRefund(WxRefundParam wxRefundParam) {
        try {
            Map<String, String> params = RefundModel.builder()
                    .appid(WeChatConfig.APP_ID)
                    .mch_id(WeChatConfig.MCH_ID)
                    .nonce_str(WxPayKit.generateStr())
                    .transaction_id(wxRefundParam.getTransactionId())
                    .out_trade_no(wxRefundParam.getOutTradeNo())
                    .out_refund_no(WxPayKit.generateStr())
                    .total_fee(String.valueOf(wxRefundParam.getTotalFee().multiply(new BigDecimal(100)).intValue()))
                    .refund_fee("退款金额")
                    .notify_url("回调地址 = 外网域名+api地址")
                    .build()
                    .createSign(WeChatConfig.API_SECRET, SignType.MD5);
            //获取证书路径
            File file = ResourceUtils.getFile(WeChatConfig.CERT_PATH_P12);
            FileInputStream certStream = new FileInputStream(file);
            String refundStr = WxPayApi.orderRefund(false, params, certStream, WeChatConfig.MCH_ID);
            log.info("refundStr: {}", refundStr);
            return WXPayUtil.xmlToMap(refundStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 微信退款成功回调通知
     *
     * @param request 回调信息
     * @return
     */
    @Override
    public String weChatRefundCallback(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        log.info("退款通知: {}" + xmlMsg);
        //XML格式字符串转换为Map
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String returnCode = params.get("return_code");
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        if (WxPayKit.codeIsOk(returnCode)) {
            try {
                String reqInfo = params.get("req_info");
                //解密数据
                String decryptData = WxPayKit.decryptData(reqInfo, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey());
                log.info("退款通知解密后的数据=" + decryptData);
                Map<String, String> aesMap = WxPayKit.xmlToMap(decryptData);
                //String outRefundNo = aesMap.get("out_refund_no");
                // 更新订单信息
                // 发送通知等
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 获取微信退款详情
     *
     * @param wxRefundParam 微信退款参数类
     * @return
     */
    @Override
    public Map<String, String> weChatQueryRefund(WxRefundParam wxRefundParam) {
        Map<String, String> params = RefundQueryModel.builder()
                .appid(WeChatConfig.APP_ID)
                .mch_id(WeChatConfig.MCH_ID)
                .nonce_str(WXPayUtil.generateNonceStr())
                .transaction_id(wxRefundParam.getTransactionId())
                .out_trade_no(wxRefundParam.getOutTradeNo())
                .out_refund_no(wxRefundParam.getOutRefundNo())
                .refund_id(wxRefundParam.getRefundId())
                .build()
                .createSign(WeChatConfig.API_SECRET, SignType.MD5);
        String resultStr = WxPayApi.orderRefundQuery(false, params);
        Map<String, String> map = null;
        try {
            map = WXPayUtil.xmlToMap(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 企业转账到零钱  微信 方式二
     *
     * @param chatTransferParam 微信转账参数类
     * @return
     */
    @Override
    public Map<String, String> weChatPaymentToChange(WeChatTransferParam chatTransferParam) {
        chatTransferParam.setPartnerTradeNo("商户号");
        Map<String, String> params = TransferModel.builder()
                .mch_appid(WeChatConfig.APP_ID)
                .mchid(WeChatConfig.MCH_ID)
                .nonce_str(WxPayKit.generateStr())
                .partner_trade_no(chatTransferParam.getPartnerTradeNo())
                .openid(chatTransferParam.getOpenId())
                .check_name("NO_CHECK")
                .amount(String.valueOf(chatTransferParam.getAmount().multiply(new BigDecimal(100)).intValue()))
                .desc(chatTransferParam.getDesc())
                .build()
                .createSign(WeChatConfig.API_SECRET, SignType.MD5, false);
        log.info("params {}", params);
        //获取证书路径
        File file = null;
        try {
            file = ResourceUtils.getFile(WeChatConfig.CERT_PATH_P12);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //文件输入流
        //FileInputStream certStream = new FileInputStream(file);
        //提现
        String transfers = WxPayApi.transfers(params, file.toString(), WeChatConfig.MCH_ID);
        log.info("提现结果 {}" + transfers);
        Map<String, String> map = null;
        try {
            map = WXPayUtil.xmlToMap(transfers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        if (WxPayKit.codeIsOk(returnCode) && WxPayKit.codeIsOk(resultCode)) {
            // 提现成功
        } else {
            // 提现失败
        }
        return map;
    }


    /**
     * 查询企业付款到零钱
     *
     * @param chatTransferParam 微信转账参数类
     * @return
     */
    @Override
    public String queryBusinessPaymentToChange(WeChatTransferParam chatTransferParam) {
        try {
            Map<String, String> params = GetTransferInfoModel.builder()
                    .nonce_str(WxPayKit.generateStr())
                    .partner_trade_no(chatTransferParam.getPartnerTradeNo())
                    .mch_id(WeChatConfig.MCH_ID)
                    .appid(WeChatConfig.APP_ID)
                    .build()
                    .createSign(WeChatConfig.API_SECRET, SignType.HMACSHA256, false);
            //获取证书路径
            File file = ResourceUtils.getFile(WeChatConfig.CERT_PATH_P12);
            FileInputStream certStream = new FileInputStream(file);
            return WxPayApi.getTransferInfo(params, certStream, WeChatConfig.MCH_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 获取RSA加密公钥
     *
     * @return 证书
     */
    @Override
    public Map<String, String> getPublicKey() {
        try {
            Map<String, String> params = new HashMap<String, String>(4);
            params.put("mch_id", WeChatConfig.MCH_ID);
            params.put("nonce_str", String.valueOf(System.currentTimeMillis()));
            params.put("sign_type", "MD5");
            String createSign = WxPayKit.createSign(params, WeChatConfig.API_SECRET, SignType.MD5);
            params.put("sign", createSign);
            //获取证书路径
            File file = ResourceUtils.getFile(WeChatConfig.CERT_PATH_P12);
            //FileInputStream certStream = new FileInputStream(file);
            String publicKey = WxPayApi.getPublicKey(params, file.toString(), WeChatConfig.MCH_ID);
            Map<String, String> map = WXPayUtil.xmlToMap(publicKey);
            System.out.println(map.get("pub_key"));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("系统繁忙，请稍后重试");
        }
    }


    /**
     * 获取平台证书
     *
     * @return
     */
    @Override
    public Map<String, Object> getPlatformCertificate() {
        // 获取平台证书列表
        try {
            IJPayHttpResponse response = WxPayApi.v3(
                    RequestMethod.GET,
                    WxDomain.CHINA.toString(),
                    WxApiType.GET_CERTIFICATES.toString(),
                    WeChatConfig.MCH_ID,
                    getSerialNumber(),
                    null,
                    WeChatConfig.keyPath,
                    ""
            );
            //String timestamp = response.getHeader("Wechatpay-Timestamp");
            //String nonceStr = response.getHeader("Wechatpay-Nonce");
            String serialNumber = response.getHeader("Wechatpay-Serial");
            //String signature = response.getHeader("Wechatpay-Signature");
            String body = response.getBody();
            int status = response.getStatus();

            log.info("serialNumber: {}", serialNumber);
            log.info("status: {}", status);
            log.info("body: {}", body);
            int isOk = 200;
            if (status == isOk) {
                cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
                JSONArray dataArray = jsonObject.getJSONArray("data");
                // 默认认为只有一个平台证书
                cn.hutool.json.JSONObject encryptObject = dataArray.getJSONObject(0);
                JSONObject encryptCertificate = encryptObject.getJSONObject("encrypt_certificate");
                String associatedData = encryptCertificate.getStr("associated_data");
                String cipherText = encryptCertificate.getStr("ciphertext");
                String nonce = encryptCertificate.getStr("nonce");
                String serialNo = encryptObject.getStr("serial_no");
                //平台证书文件要存在，即使是空的
                String platSerialNo = savePlatformCert(associatedData, nonce, cipherText, WeChatConfig.platformCertPath);
                log.info("平台证书序列号: {} serialNo: {}", platSerialNo, serialNo);
            }
            // 根据证书序列号查询对应的证书来验证签名结果
            boolean verifySignature = WxPayKit.verifySignature(response, WeChatConfig.platformCertPath);
            System.out.println("verifySignature:" + verifySignature);
            Map<String, Object> maps = (Map<String, Object>) JSON.parse(body);
            return maps;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("系统繁忙，请稍后重试");
        }
    }


    /**
     * 保存平台证书
     *
     * @param associatedData 关联数据
     * @param nonce          随机字符串
     * @param cipherText     密文
     * @param certPath       证书路径
     * @return
     */
    private String savePlatformCert(String associatedData, String nonce, String cipherText, String certPath) {
        try {
            AesUtil aesUtil = new AesUtil(WeChatConfig.API_V3_SECRET.getBytes(StandardCharsets.UTF_8));
            // 平台证书密文解密
            // encrypt_certificate 中的  associated_data nonce  ciphertext
            String publicKey = aesUtil.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), cipherText);
            // 保存证书
            FileWriter writer = new FileWriter(certPath);
            writer.write(publicKey);
            // 获取平台证书序列号
            X509Certificate certificate = PayKit.getCertificate(new ByteArrayInputStream(publicKey.getBytes()));
            return certificate.getSerialNumber().toString(16).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    /**
     * 企业付款到银行 方式二
     *
     * @param chatTransferParam 微信转账参数类
     * @return
     */
    @Override
    public Map<String, String> corporatePaymentToBankCard(WeChatTransferParam chatTransferParam) {
        try {
            String partnerTradeNo = "商户单号";
            chatTransferParam.setPartnerTradeNo(partnerTradeNo);
            //假设获取到的RSA加密公钥为PUBLIC_KEY(PKCS#8格式)
            String PUBLIC_KEY = WeChatConfig.PUB_KEY;

            Map<String, String> data = new HashMap<String, String>(10);
            data.put("mch_id", WeChatConfig.MCH_ID);
            data.put("partner_trade_no", chatTransferParam.getPartnerTradeNo());
            data.put("nonce_str", WxPayKit.generateStr());
            //收款方银行卡号
            data.put("enc_bank_no", RsaKit.encryptByPublicKeyByWx(chatTransferParam.getEncBankNo(), PUBLIC_KEY));
            //收款方用户名
            data.put("enc_true_name", RsaKit.encryptByPublicKeyByWx(chatTransferParam.getEncTrueName(), PUBLIC_KEY));
            //收款方开户行
            data.put("bank_code", WXPayBank.getBankCode(chatTransferParam.getBankCode()));
            data.put("amount", String.valueOf(chatTransferParam.getAmount().multiply(new BigDecimal(100)).intValue()));
            data.put("desc", chatTransferParam.getDesc());
            data.put("sign", WxPayKit.createSign(data, WeChatConfig.API_SECRET, SignType.MD5));
            //获取证书路径
            File file = ResourceUtils.getFile(WeChatConfig.CERT_PATH_P12);
            FileInputStream certStream = new FileInputStream(file);
            String str = WxPayApi.payBank(data, certStream, WeChatConfig.MCH_ID);
            System.out.println(str);
            return WXPayUtil.xmlToMap(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 查询企业付款到银行卡
     *
     * @param chatTransferParam 微信转账参数类
     * @return 订单数据
     */
    @Override
    public String queryCorporatePaymentToBankCard(WeChatTransferParam chatTransferParam) {
        try {
            Map<String, String> params = new HashMap<String, String>(4);
            params.put("mch_id", WeChatConfig.MCH_ID);
            params.put("partner_trade_no", chatTransferParam.getPartnerTradeNo());
            params.put("nonce_str", System.currentTimeMillis() + "");
            params.put("sign", WxPayKit.createSign(params, WeChatConfig.API_SECRET, SignType.MD5));
            //获取证书路径
            File file = ResourceUtils.getFile(WeChatConfig.CERT_PATH_P12);
            FileInputStream certStream = new FileInputStream(file);
            return WxPayApi.queryBank(params, certStream, WeChatConfig.MCH_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 获取微信订单详情
     *
     * @param wxRefundParam 微信退款参数类
     * @return
     */
    @Override
    public Map<String, String> weChatOrderQuery(WxRefundParam wxRefundParam) {
        Map<String, String> params = RefundQueryModel.builder()
                .appid(WeChatConfig.APP_ID)
                .mch_id(WeChatConfig.MCH_ID)
                .nonce_str(WxPayKit.generateStr())
                .transaction_id(wxRefundParam.getTransactionId())
                .out_trade_no(wxRefundParam.getOutTradeNo())
                .build()
                .createSign(WeChatConfig.API_SECRET, SignType.MD5);
        String resultStr = WxPayApi.orderQuery(params);
        Map<String, String> map = null;
        try {
            map = WXPayUtil.xmlToMap(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 微信app支付
     *
     * @param payParam 微信支付参数类
     * @return
     */
    @Override
    public Map<String, String> weChatAppPayment(WXPayParam payParam) {
        try {
            Map<String, String> params = com.ijpay.wxpay.model.UnifiedOrderModel
                    .builder()
                    .appid(WeChatConfig.APP_ID)
                    .mch_id(WeChatConfig.MCH_ID)
                    .nonce_str(WxPayKit.generateStr())
                    .body(payParam.getBody())
                    .attach(payParam.getAttach())
                    .out_trade_no("商户单号")
                    .total_fee(payParam.getTotalFee().multiply(new BigDecimal(100)).intValue() + "")
                    .spbill_create_ip(IPHelper.getIpAddr())
                    .notify_url("外网IP地址" + WeChatConfig.Payment_Callback)
                    .trade_type(WxPayConstants.TradeType.APP)
                    .build()
                    .createSign(WeChatConfig.API_SECRET, SignType.HMACSHA256);

            //统一下单
            String xmlResult = WxPayApi.pushOrder(false, params);
            System.out.println(xmlResult);
            Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
            String returnCode = result.get("return_code");
            String resultCode = result.get("result_code");
            if (WxPayKit.codeIsOk(returnCode) && WxPayKit.codeIsOk(resultCode)) {
                // 以下字段在 return_code 和 result_code 都为 SUCCESS返回
                String prepayId = result.get("prepay_id");
                //签名
                Map<String, String> packageParams = WxPayKit.appPrepayIdCreateSign(WeChatConfig.APP_ID, WeChatConfig.MCH_ID, prepayId, WeChatConfig.API_SECRET, SignType.HMACSHA256);
                //String jsonStr = JSON.toJSONString(packageParams);
                log.info("返回apk的参数:" + packageParams);
                return packageParams;
            } else {
                result.put("des", "支付失败");
                result.put("returnMsg", result.get("return_msg"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


    /**
     * 微信app支付 V3版本
     * 统一下单
     *
     * @param param 微信支付传参类
     * @return
     */
    @Override
    public Map<String, String> weChatAppPayV3(VipOrderParam param) {
        try {
            //下单金额
            BigDecimal money = param.getAmount().multiply(BigDecimal.valueOf(100d));
            //统一下单参数封装
            String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3);
            UnifiedOrderModel unifiedOrderModel = new UnifiedOrderModel()
                    .setAppid(WeChatConfig.APP_ID)
                    .setMchid(WeChatConfig.MCH_ID)
                    .setDescription("备注")
                    .setOut_trade_no("商户单号")
                    .setTime_expire(timeExpire)
                    .setNotify_url("外网ip地址" + WeChatConfig.Payment_Callback)
                    .setAmount(new Amount().setTotal(money.intValue()));
            log.info("统一下单参数 {}", JSONUtil.toJsonStr(unifiedOrderModel));

            IJPayHttpResponse response = WxPayApi.v3(
                    RequestMethod.POST,
                    WxDomain.CHINA.toString(),
                    WxApiType.APP_PAY.toString(),
                    WeChatConfig.MCH_ID,
                    getSerialNumber(),
                    null,
                    WeChatConfig.keyPath,
                    JSONUtil.toJsonStr(unifiedOrderModel)
            );
            log.info("统一下单响应 {}", response);
            // 根据证书序列号查询对应的证书来验证签名结果
            boolean verifySignature = WxPayKit.verifySignature(response, WeChatConfig.platformCertPath);
            log.info("verifySignature {}", verifySignature);
            if (verifySignature) {
                String body = response.getBody();
                cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
                String prepayId = jsonObject.getStr("prepay_id");
                Map<String, String> map = WxPayKit.appPrepayIdCreateSign(WeChatConfig.APP_ID, WeChatConfig.MCH_ID, prepayId, WeChatConfig.keyPath,SignType.HMACSHA256);
                log.info("唤起支付参数 {}", map);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CustomException("系统繁忙，请稍后重试");
    }


}
